import { config } from '../config/env.js'
import { APIError } from '../middleware/error.js'
import { retryWithBackoff } from '../utils/retry.js'

export interface EmotionItem {
  name: string
  intensity: number
  color: string
  icon: string
}

export interface EmotionReport {
  emotions: EmotionItem[]
  suggestions: string[]
  summary: string
  timestamp: Date
}

export interface AnalyzeEmotionResponse {
  success: boolean
  report: EmotionReport
  imagePrompt: string
  error?: string
}

const EMOTION_COLORS: Record<string, string> = {
  happy: '#FFD700',
  sad: '#4169E1',
  anxious: '#FF6347',
  calm: '#98FB98',
  angry: '#DC143C',
  excited: '#FF69B4',
  confused: '#9370DB',
  hopeful: '#87CEEB',
}

const EMOTION_ICONS: Record<string, string> = {
  happy: '😊',
  sad: '😢',
  anxious: '😰',
  calm: '😌',
  angry: '😠',
  excited: '🤩',
  confused: '😕',
  hopeful: '🌟',
}

export async function analyzeEmotion(text: string): Promise<AnalyzeEmotionResponse> {
  try {
    const response = await retryWithBackoff(async () => {
      return await fetch(`${config.openai.endpoint}/chat/completions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${config.openai.apiKey}`,
      },
      body: JSON.stringify({
        model: 'gpt-3.5-turbo',
        messages: [
          {
            role: 'system',
            content: `你是一位专业的情绪分析专家和心理咨询师。请深入分析用户的文字并返回 JSON 格式的响应，包含以下内容：

1. emotions: 检测到的所有情绪数组，每个情绪包含名称和强度（0-100）
2. suggestions: 5-8 条详细的、可操作的中文建议（每条建议至少30字）
3. summary: 详细的情绪状态中文总结（至少100字）

重要要求：
- emotions 数组必须包含所有检测到的情绪，不要只返回最强的一个
- 至少返回 3-6 种不同的情绪，按强度从高到低排序
- **关键要求：所有情绪的 intensity 值加起来必须等于 100**（这是百分比分布）
- 每个情绪的 intensity 代表该情绪在整体情绪中所占的百分比
- 所有建议（suggestions）必须使用中文，每条建议要具体、详细、可操作
- 建议要包含具体的行动步骤，不要只是泛泛而谈
- 总结（summary）必须使用中文，要深入分析用户的情绪状态、可能的原因、以及对生活的影响
- 总结要有同理心，让用户感受到被理解
- 情绪名称（emotion name）使用英文（如 happy, sad, anxious, calm, angry, excited, confused, hopeful 等）

返回格式示例（注意所有 intensity 加起来 = 100）：
{
  "emotions": [
    {"name": "happy", "intensity": 40},
    {"name": "excited", "intensity": 25},
    {"name": "hopeful", "intensity": 20},
    {"name": "calm", "intensity": 10},
    {"name": "anxious", "intensity": 5}
  ], 
  "suggestions": [
    "建议1：具体的行动步骤，包含为什么这样做以及如何执行，至少30字...",
    "建议2：另一个详细的建议...",
    "建议3：第三个具体建议..."
  ], 
  "summary": "详细的情绪分析总结，至少100字，包含对用户情绪的深入理解、可能的原因分析、以及这种情绪状态对生活的影响..."
}`
          },
          {
            role: 'user',
            content: text
          }
        ],
        temperature: 0.7,
      }),
      signal: AbortSignal.timeout(config.api.timeout),
    })
    })

    if (!response.ok) {
      if (response.status === 429) {
        throw new APIError('Rate limit exceeded', 429, true)
      }
      throw new APIError(`API request failed: ${response.statusText}`, response.status, true)
    }

    const data = await response.json() as {
      choices?: Array<{
        message?: {
          content?: string
        }
      }>
    }

    const content = data.choices?.[0]?.message?.content
    if (!content) {
      throw new APIError('Invalid API response format', 500, true)
    }

    // Parse the JSON response from GPT
    const parsed = JSON.parse(content) as {
      emotions?: Array<{ name: string; intensity: number }>
      suggestions?: string[]
      summary?: string
    }

    if (!parsed.emotions || !parsed.suggestions || !parsed.summary) {
      throw new APIError('Incomplete emotion analysis response', 500, true)
    }

    // Build emotion items with colors and icons
    const emotions: EmotionItem[] = parsed.emotions.map(e => ({
      name: e.name,
      intensity: Math.max(0, Math.min(100, e.intensity)),
      color: EMOTION_COLORS[e.name.toLowerCase()] || '#808080',
      icon: EMOTION_ICONS[e.name.toLowerCase()] || '😐',
    }))

    // Generate image prompt from emotions
    const imagePrompt = generateImagePrompt(emotions, parsed.summary)

    const report: EmotionReport = {
      emotions,
      suggestions: parsed.suggestions,
      summary: parsed.summary,
      timestamp: new Date(),
    }

    return {
      success: true,
      report,
      imagePrompt,
    }
  } catch (error) {
    if (error instanceof APIError) {
      throw error
    }
    
    if (error instanceof Error) {
      if (error.name === 'TimeoutError') {
        throw new APIError('Request timeout', 408, true)
      }
      throw new APIError(error.message, 500, true)
    }
    
    throw new APIError('Unknown error occurred', 500, true)
  }
}

export function generateImagePrompt(emotions: EmotionItem[], summary: string): string {
  // Extract top 3 emotions by intensity
  const topEmotions = [...emotions]
    .sort((a, b) => b.intensity - a.intensity)
    .slice(0, 3)
    .map(e => e.name)

  // Create a descriptive prompt with Moebius art style
  const emotionKeywords = topEmotions.join(', ')
  const prompt = `Artistic visualization of emotions: ${emotionKeywords}. ${summary}. Moebius art style, Jean Giraud inspired, clean lines, detailed linework, sci-fi aesthetic, surreal landscapes, vibrant colors, European comic book style, intricate details, dreamlike atmosphere, futuristic elements.`

  return prompt
}
